import datetime

from sqlalchemy import Column, DateTime, BigInteger, String, Index
from sqlalchemy.orm import Session, relationship
from common.database import Base
from common.database import SessionMixin

__all__ = ['QosTrafficStatistics']


class QosTrafficStatistics(Base, SessionMixin):
    """
    流量统计信息
    """
    __tablename__ = "qos_traffic_statistics"
    item = Column(String(80), nullable=False, comment='指标名称 pv|uv|japi_qpm每分查询率(QPS，Queries-per-minute)')
    value = Column(BigInteger, nullable=False, comment='指标数值')
    create_time = Column(DateTime, default=datetime.datetime.now, nullable=False, comment="创建时间")

    __table_args__ = (
        Index('idx_qos_traffic_statistics_item', 'item', unique=False),
        Index('idx_qos_traffic_statistics_item_create_time', 'item', 'create_time', unique=False),
        {
            'mysql_engine': 'innodb',
            'mysql_charset': 'utf8mb4',
            'mysql_collate': 'utf8mb4_unicode_ci',
            'extend_existing': True
        }
    )

    def __repr__(self):
        return "<item='{}',value='{}',create_time='{}'>".format(self.item, self.value, self.create_time)



    # 获取item最新的值
    @classmethod
    def get_item_last_value(cls, db: Session, item):
        try:
            object_info = db.query(cls).filter(
                cls.item == item
            ).order_by(cls.create_time.desc()).to_dict_first()
            if not object_info:
                return {}
        except Exception as e:
            logger.exception(f'{sys._getframe().f_code.co_name} {e}')
            return None

        return object_info